package com.hb.core.config.handler;

import com.hb.core.pojo.JSONArrayProperty;
import com.hb.core.pojo.JSONObjectProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * describe:
 *
 * @author zhongdl
 * @date 2021/12/01
 */
@Slf4j
@MappedJdbcTypes(JdbcType.LONGVARCHAR)
@MappedTypes(JSONArrayProperty.class)
public class JSONArrayTypeHandler extends BaseTypeHandler<JSONArrayProperty> implements HandlerConverter {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, JSONArrayProperty jsonEntity, JdbcType jdbcType) throws SQLException {
        ps.setString(i, jsonEntity.toString());
    }

    @Override
    public JSONArrayProperty getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String result = rs.getString(columnName);
        return convert(result);
    }

    @Override
    public JSONArrayProperty getNullableResult(ResultSet rs, int columnName) throws SQLException {
        String result = rs.getString(columnName);
        return convert(result);
    }

    @Override
    public JSONArrayProperty getNullableResult(CallableStatement cs, int columnName) throws SQLException {
        String result = cs.getString(columnName);
        return convert(result);
    }

    private JSONArrayProperty convert(String result) {
        JSONArrayProperty convert = convert(result, JSONArrayProperty.class);
        if (convert == null) {
            log.warn("[{}] 无法转换成 com.hb.core.pojo.JSONInfo", result);
            return null;
        }
        return convert;
    }

}
